package model

import (
	"gorm.io/gorm"
	"math/rand"
	"next-vue-backend/utils/errmsg"
	"time"
)

type Verse struct {
	gorm.Model
	Title string `gorm:"type:varchar(40); not null" json:"title" validate:"required" label:"诗词名称"`
	Container string `gorm:"type:varchar(100); not null" json:"container" validate:"required" label:"诗词内容"`
	Dynasty string `gorm:"type:varchar(10); not null" json:"dynasty" label:"朝代"`
	Author string `gorm:"type:varchar(20); not null" json:"author" label:"作者"`
}

// CreateVerse 新增诗词
func CreateVerse (data *Verse) int {
	err := db.Create(&data).Error
	if err != nil {
		return errmsg.ERROR
	}
	return errmsg.SSUCCESS
}

// GetVerses 查看诗词列表
func GetVerses (pageSize int, pageNum int) ([]Verse, int, int64) {
	var verses []Verse
	var total int64
	err = db.Limit(pageSize).Offset((pageNum - 1) * pageSize).Find(&verses).Count(&total).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return  nil, errmsg.ERROR,  0
	}
	return  verses, errmsg.SSUCCESS, total
}

// GetRandomVerse 随机查看单条诗词
func GetRandomVerse () (Verse, int) {
	var verses []Verse
	var verse Verse
	var total int64
	err := db.Find(&verses).Count(&total).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return  verse,errmsg.ERROR
	}
	// 获取当前诗词列表中随机一条
	randomErr := db.Where("id = ?", RandInt64(1, total)).Find(&verse).Error
	if randomErr != nil && randomErr != gorm.ErrRecordNotFound {
		return  verse,errmsg.ERROR
	}
	return  verse, errmsg.SSUCCESS
}

// EditVerse 编辑诗词
func EditVerse (id int, data *Verse) int {
	var verse Verse
	var maps = make(map[string] interface{})
	maps["title"] = data.Title
	maps["container"] = data.Container
	maps["dynasty"] = data.Dynasty
	maps["author"] = data.Author
	err = db.Model(&verse).Where("id = ?", id).Updates(maps).Error
	if err != nil {
		return errmsg.ERROR
	}
	return errmsg.SSUCCESS
}

// DeleteVerse 删除诗词
func DeleteVerse (id int) int {
	var verse Verse
	err = db.Where("id = ? ", id).Delete(&verse).Error
	if err != nil {
		return errmsg.ERROR
	}
	return errmsg.SSUCCESS
}

// RandInt64 创建随机整数
func RandInt64(min, max int64) int64 {
	if min >= max || max == 0 {
		return max
	}
	rand.Seed(time.Now().UnixNano())
	return rand.Int63n(max-min) + min
}